package com.minshenglife.zanzan.web.weixin.service;

import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.minshenglife.zanzan.entity.AccessToken;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.service.AccessTokenAndJsapiTicketService;
import com.minshenglife.zanzan.entity.AccessTokenAndJsapiTicket;
import com.minshenglife.zanzan.service.AccessTokenService;

@Component
public class WXAccTokenService {

	Logger log = LoggerFactory.getLogger(WXAccTokenService.class);

	@Resource
	AccessTokenService accessTokenService;
	@Resource
	AccessTokenAndJsapiTicketService accessService;
	/**
	 * 获取微信token
	 * 
	 * @return
	 * @throws Exception
	 */
//	public synchronized String getWXAccToken() throws Exception {
//		String flag = WXKeys.WX_APPID;
//		AccessToken at = accessTokenService.getWXAccessToken(flag);
//		if (at == null) {
//			log.debug("start new create access_token");
//			String token = WXBaseService.getWXAccessToken();
//			accessTokenService.insertWXAccessToken(flag, token);
//			return token;
//		} else {
//			// 校验时间是否超过
//			if (new Date().getTime() >= at.getEnd_time().getTime()) {
//				log.debug("access_token 失效 ，重新 create access_token");
//				// 重新录入
//				String token = WXBaseService.getWXAccessToken();
//				accessTokenService.insertWXAccessToken(flag, token);
//				return token;
//			} else {
//				return at.getAccessToken();
//			}
//		}
//	}

	public String getWXAccToken() throws Exception {
		try{
			AccessTokenAndJsapiTicket token = accessService.getAccessTokenAndJsapiTicket(WXKeys.WX_APPID);
			return token.getAccessToken();
		}catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取 民生保险CMO在线 服务号 token
	 * 
	 * @return
	 * @throws Exception
	 */
	public synchronized String getEMOWXAccToken() throws Exception {
		String flag = WXKeys.WX_EMO_APPID;
		AccessToken at = accessTokenService.getWXAccessToken(flag);
		if (at == null) {
			log.debug("start new create access_token");
			String token = EMOWXBaseServcie.getWXAccessToken();
			accessTokenService.insertWXAccessToken(flag, token);
			return token;
		} else {
			// 校验时间是否超过
			if (new Date().getTime() >= at.getEnd_time().getTime()) {
				log.debug("access_token 失效 ，重新 create access_token");
				// 重新录入
				String token = EMOWXBaseServcie.getWXAccessToken();
				accessTokenService.insertWXAccessToken(flag, token);
				return token;
			} else {
				String accessToken = at.getAccessToken();
				if (accessToken != null && !accessToken.equals("")
						&& !accessToken.equals(" ")) {
					return accessToken;
				} else {
					accessToken = EMOWXBaseServcie.getWXAccessToken();
					accessTokenService.insertWXAccessToken(flag, accessToken);
					return accessToken;
				}
			}
		}
	}
}
